package com.bxd.baodan.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.fragment.AdviserJudgeFragment;
import com.bxd.baodan.fragment.AdviserProductFragment;
import com.bxd.baodan.fragment.BaseFragment;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.list.AdviserWenwenFragment;
import com.bxd.baodan.util.ImageUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.PagerSlidingTabStrip;
import com.bxd.baodan.widget.StarBarView;
import com.tencent.TIMConversationType;
import com.tencent.qcloud.timchat.ui.ChatActivity;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class AdviserActivity extends BaseActivity {

    private ViewPager pager;
    private List<BaseFragment> list = new ArrayList<BaseFragment>();
    private FragmentPagerAdapter mAdapter;
    PagerSlidingTabStrip tabs;
    final String[] titles = {"咨询服务", "用户评价", "推荐产品"};

    private Context context;
    String agentId;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //  initImmersionBar(R.color.green_lab);
        setContentView(R.layout.activity_adviser);
        findViewById(R.id.bar_content).setBackground(getResources().getDrawable(R.color.green_lab));
        ((TextView) findViewById(R.id.bar_tv_title)).setTextColor(getResources().getColor(R.color.white));
        setActionBarTitle("顾问主页");

        findViewById(R.id.bar_line).setVisibility(View.GONE);
        context = this;

        agentId = getIntent().getExtras().getString("params");
        //头布局及数据
        initHead();
        //tabtrip及fragment
        initView();
    }

    private void initHead() {


        NetUtil headNet = new NetUtil(this, JsonApi.AGENT_DETAIL);
        headNet.setParams("params", agentId);

        headNet.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {
                    final UserItem item = new Gson().fromJson(JSONUtil.getData(result), UserItem.class);
                    initHeadView(item);
                }
            }
        });


    }

    private void initHeadView(final UserItem item) {

        TextView nianxianTv;
        TextView fuwuTv;
        TextView huidaTv;

        TextView name;
        TextView company;
        TextView distance;
        ImageView image;
        TextView adept_field;
        ImageView mircoread_url;
        RelativeLayout relative_show;

        //chat verify_level score
        TextView chat;
        TextView verify_level;
        TextView score;
        StarBarView starBar;
        ImageView verify_icon;


        nianxianTv = (TextView) findViewById(R.id.nianxian_tv);
        fuwuTv = (TextView) findViewById(R.id.fuwu_tv);
        huidaTv = (TextView) findViewById(R.id.huida_tv);


        name = (TextView) findViewById(R.id.tv_name);
        company = (TextView) findViewById(R.id.tv_company);
        distance = (TextView) findViewById(R.id.tv_distance);
        image = (ImageView) findViewById(R.id.image_avtar);


        adept_field = (TextView) findViewById(R.id.tv_shanchang);



        //todo  holder chat verify_level score verify_icon
        chat = (TextView) findViewById(R.id.chat_status);
        verify_level = (TextView) findViewById(R.id.verify_level);
        score = (TextView) findViewById(R.id.score);
        starBar = (StarBarView) findViewById(R.id.star_bar);
        verify_icon = (ImageView) findViewById(R.id.verify_icon);

        nianxianTv.setText(item.workTime);
        fuwuTv.setText(item.serviceCount);
        huidaTv.setText(item.answerCount);


        if (item.score != null) {
            score.setText(Float.parseFloat(item.score) + "分");
            float star = Float.parseFloat(item.score);
            starBar.setStarRating(star);
        }


        // TODO: 2017/3/27 item 添加字段 需要
        //answer信息
        // TODO: 2017/3/27 item 添加字段 需要
        String verify = "";
        int level = item.ua_title;
        int verColor = R.color.white;
        int drawableLeft = R.color.transparent;

        switch (level) {
            case 0:
                break;
            case 4:
                verify = "保险管家";
                verColor = R.color.guanja;
                drawableLeft = R.drawable.round_corner_yellow;
                break;
            case 2:
                verify = "保险精英";
                verColor = R.color.jingying;
                drawableLeft = R.drawable.round_corner_blue_jingying;
                break;
            case 1:
                verify = "保险达人";
                verColor = R.color.daren;
                drawableLeft = R.drawable.round_corner_green;
                break;
            case 3:
                verify = "保险专家";
                verColor = R.color.zhuanjia;
                drawableLeft = R.drawable.round_corner_red_zhuanjia;
                break;
            default:
                break;
        }


        verify_level.setBackground(context.getResources().getDrawable(drawableLeft));


        verify_level.setText(verify);
        verify_level.setTextColor(context.getResources().getColor(verColor));


        chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //顾问一对一点击
                MobclickAgent.onEvent(context, "v5_5_1_SY_zgw_1v1");
                if (LoginInfo.getInstance(App.getContext()).isLogin()) {
                    ChatActivity.navToChat(context, item.getU_id() + "", TIMConversationType.C2C);
                } else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                    ((Activity) context).overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                }
            }
        });


        // TODO: 2017/3/27 身份认证要改
        if (item.getAgent_mark() != null && item.getAgent_mark().length > 0
                && Arrays.asList(item.getAgent_mark()).contains("6")) {
            verify_icon.setVisibility(View.VISIBLE);
        } else {
            verify_icon.setVisibility(View.GONE);
        }

        image.setImageResource(R.drawable.empty_person);
        ImageUtil.setAvatarToRounderCorner(context, item.getUe_avatar(),
                image, true);
        name.setText(item.getUe_realname());// 显示代理人姓名
        company.setText("机构：" + item.getCompanyname());
        try {
            distance.setText("地区：" + item.getCity());
        } catch (Exception e) {
        }


        if (item.getAdept_field() != null && !item.getAdept_field().equals("")) {
            adept_field.setText("擅长：" + item.getAdept_field());
        }


    }


    private void initView() {
        AdviserWenwenFragment wenFragment = new AdviserWenwenFragment();
        wenFragment.setNetUtil(getWenwen());
        wenFragment.mMode = PullToRefreshBase.Mode.PULL_FROM_END;
        list.add(wenFragment);

        AdviserJudgeFragment adviserJudgeFragment = new AdviserJudgeFragment();
        adviserJudgeFragment.setNetUtil(getJudge());
        list.add(adviserJudgeFragment);

        AdviserProductFragment adviserProductFragment = new AdviserProductFragment();
        adviserProductFragment.mMode = PullToRefreshBase.Mode.PULL_FROM_END;
        adviserProductFragment.setNetUtil(getProduce());
        list.add(adviserProductFragment);


        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return list.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                // TODO Auto-generated method stub
                return list.get(arg0);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        };

        pager = (ViewPager) findViewById(R.id.pager);
        tabs = (PagerSlidingTabStrip) findViewById(R.id.strip);
        pager.setAdapter(mAdapter);
        tabs.setViewPager(pager);


        setTabsValue();
        //设置小红点,item从0开始计算
        //        tabs.setMsgToast(1, true);

    }


    private void setTabsValue() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        // 设置Tab底部选中的指示器Indicator的高度
        tabs.setIndicatorHeight(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.5f, dm));
        // 设置Tab底部选中的指示器 Indicator的颜色
        tabs.setIndicatorColorResource(R.color.green_lab);
        //设置指示器Indicatorin是否跟文本一样宽，默认false
        tabs.setIndicatorinFollowerTv(true);
        //设置小红点提示，item从0开始计算，true为显示，false为隐藏
        //        tabs.setMsgToast(2, true);
        //设置红点滑动到当前页面自动消失,默认为true
        tabs.setMsgToastPager(true);
        //设置Tab标题文字的颜色
        tabs.setTextColor(getResources().getColor(R.color.black));
        // 设置Tab标题文字的大小
        tabs.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, dm));
        // 设置选中的Tab文字的颜色
        tabs.setSelectedTextColorResource(R.color.green_lab);
        //设置Tab底部分割线的高度
        tabs.setUnderlineHeight(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, dm));
        //设置Tab底部分割线的颜色
        tabs.setUnderlineColorResource(R.color.transparent);
        // 设置点击某个Tab时的背景色,设置为0时取消背景色tabs.setTabBackground(0);
        //        tabs.setTabBackground(R.drawable.bg_tab);
        tabs.setTabBackground(0);
        // 设置Tab是自动填充满屏幕的
        tabs.setShouldExpand(true);

        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    MobclickAgent.onEvent(App.getContext(), "v5_5_1_SY_zgw_zy_zxfw");
                } else if (position == 1) {
                    MobclickAgent.onEvent(App.getContext(), "v5_5_1_SY_zgw_zy_yhpj");
                } else if (position == 2) {
                    MobclickAgent.onEvent(App.getContext(), "v5_5_1_SY_zgw_zy_cptj");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    public NetUtil getWenwen() {
        NetUtil netUtil = new NetUtil(this, JsonApi.QUESTION_AGENTANSWERS);
        netUtil.setParams("agentId", agentId);
        return netUtil;
    }

    public NetUtil getJudge() {
        NetUtil netUtil = new NetUtil(this, JsonApi.AGENT_COMMENTS);
        netUtil.setParams("agentId", agentId);
        return netUtil;
    }

    public NetUtil getProduce() {
        NetUtil netUtil = new NetUtil(this, JsonApi.PRODUCT_AGENTRECOMMEND);
        netUtil.setParams("agentId", agentId);
        return netUtil;
    }
}
